import { Space, Input, Button, Image, message } from 'antd';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { addBanner } from '../../api/banner';

type AddProps = {}

export const Add = (props: AddProps) => {
  

  const [alt, setAlt] = useState<string>('')
  const [link, setLink] = useState<string>('')
  const [url, setUrl] = useState('')

  const getImgUrl = () => {
    const img = document.getElementById('img') as HTMLInputElement
    const files = img && img.files
    const file = files && files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file!)
    reader.onload = function () {
      setUrl(this.result!.toString())
    }
  }
  const navigate = useNavigate()
  return (
    <Space direction='vertical' style={{ width: '100%' }}>
      <Input placeholder='提示信息' value={ alt } onChange = { e=> setAlt(e.target.value) }/>
      <Input placeholder='链接地址' value={ link } onChange = { e=> setLink(e.target.value) }/>
      <Input type="file" id='img' onChange={ getImgUrl }/>
      <div>
        预览图片:
        <Image src={ url } width = { 300 } />
      </div>
      <Button type='primary' onClick={() => {
        if (alt === '' || link === '' || url === '') {
          message.error('请先完成表单输入')
          return
        }
        addBanner({
          alt, link, img: url
        }).then(() => {
          navigate('/banner/home')
        })
      }}>添加</Button>
    </Space>
  );
}